package ajaxjs.data.service.subObject;

import java.io.File;
import java.sql.Connection;

import javax.servlet.http.HttpServletRequest;

import ajaxjs.admin.entry.CRUD;
import ajaxjs.config.Application;
import ajaxjs.data.entry.Entry;
import ajaxjs.net.upload.Upload_HTTP;
import ajaxjs.service.BaseServlet;

public class Img extends SubObject{

	public int create(){
		String str = "";
		try {
			str = upload_save2db(request, getParentTableName(), jdbcConn);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String[] strArr = str.split("#");
		
		int newlyId = Integer.parseInt(strArr[0]);
		String fileName = strArr[1];
		
		return 1;
//		return printOk("上传成功，id：" + newlyId, fileName);
	}
	
	public static String upload_save2db(HttpServletRequest request, String entryName, Connection jdbcConn){
		Upload_HTTP uploader = new Upload_HTTP(request);
		uploader.setSaveFolder("public" + File.separator + "gallery");
		uploader.upload();
				
		String id = ajaxjs.net.Request.get(request, "parentId");

		CRUD crud = new CRUD(jdbcConn){
			public String getTableName(){
				return "img";
			}
		};
		
		int newlyId = crud.create(
			new String[]{"fileName", "belongsTo", "parentId"}, 
			new String[]{
				"'" + uploader.fileName + "'", "'" + entryName + "'", id
			}
		);
		
		return newlyId + "#" + uploader.fileName;
	}
	
	public static String name = "图片";
	public static String id = "img";
	@Override
	public String getTableName() {
		return id;
	}
	/**
	 * for create
	 * @param _msg
	 * @return
	 */
	private String printOk(final String _msg, final String _fileName){
		return Application.jsRuntime.parseObj(new Object() {  
			@SuppressWarnings("unused")
			public boolean isOk = true;   
			@SuppressWarnings("unused")
			public String msg = _msg;
			@SuppressWarnings("unused")
			public String fileName = _fileName;
		});
	}
	
	@Override
	public String findList(String where){
		
		try {
			if(where != null)
				where += " AND belongsTo = '" + parentTableName + "'";
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e);
		}
		System.out.println(where);
		return super.findList(where);
	}
	@Override
	public String getName() {
		return name;
	}
	@Override
	public String getId() {
		return id;
	}

	@Override
	public Entry getPojo() {
		return pojo;
	}
}
